<?php

namespace app\common\model;

use think\Exception;
use think\Model;

class User extends Model
{
    protected $autoWriteTimestamp = true;
    protected $type = [
        'create_time'    =>  'integer',
        'update_time'     =>  'integer',
    ];
    //用户token
    public function userToken(){
        return $this->hasOne('UserToken');
    }

    //用户标签
    public function tag(){
        return $this->belongsTo('UserTag');
    }
    public function thirdLogin(){
        return $this->hasOne('ThirdLogin');
    }
    public function addresses(){
        return $this->hasMany('Address');
    }
    //用户金融产品
    public function finances(){
        return $this->hasMany('UserFinance');
    }
    //用户房产
    public function houses(){
        return $this->hasMany('UserHouse');
    }
    //用户银行卡
    public function banks(){
        return $this->hasMany('UserBank');
    }

    public function feedback(){
        return $this->hasMany('OpinionFedback');
    }

    //生成随机昵称
    public static function createNickname(){
        $prefix = '';
        for($i = 65;$i<=90;$i++){
            $wordL[] =  chr($i);
        }
        for($i=97;$i<=122;$i++){
            $wordU[] = chr($i);
        }
        $word = array_merge($wordL,$wordU);
        for ($i = 1; $i <= 4; $i++) {
            $prefix.= $word[array_rand($word)];
        }
        $nickname = str_pad(random_int(0, 99999999), 8, '0', STR_PAD_LEFT).$prefix;
        return $nickname;
    }

    public static function getAccid(){
        // 订单流水号前缀
        $prefix = config('netease.acc_prefix');
        for ($i = 0; $i < 10; $i++) {
            // 随机生成 10 位的数字
            $accid = $prefix.str_pad(random_int(0, 9999999999), 10, '0', STR_PAD_LEFT);
            // 判断是否已经存在
            if (!self::where('accid', $accid)->field('id')->find()) {
                return $accid;
            }
        }
        throw new Exception('生成云信ID失败');
    }

    public static function getMeid(){
        // 订单流水号前缀
        $prefix = config('netease.ease_prefix');
        for ($i = 0; $i < 10; $i++) {
            // 随机生成 10 位的数字
            $accid = $prefix.str_pad(random_int(0, 9999999999), 10, '0', STR_PAD_LEFT);
            // 判断是否已经存在
            if (!self::where('accid', $accid)->field('id')->find()) {
                return $accid;
            }
        }
         throw new Exception('生成 ME ID失败');
    }
}
